package order;

import model.*;
import model.Map;

import javax.swing.JOptionPane;

import java.util.*;

public class Move extends ActionOrder{

	public Move(Territory source, Player player, Territory destination,HashMap<TechnologyLevel, Integer> troopAmount){
        super(source, player, destination, troopAmount); 
    }

	protected  boolean checkOwner(){
		if(source.getOwner() != player){
			JOptionPane.showMessageDialog(null, "You can only use your own territory!");
			 return false;
		}
		if ((source.getOwner() == destination.getOwner()) ||(source.getOwner().isAlly(destination.getOwner())) ) return true;
        else {
        	JOptionPane.showMessageDialog(null, "You can only move troops between your own territory or your ally's territory!");
            return false;
         }
    }

    protected boolean checkPath(Map map){
    	if (map.routeProcess(source, destination)) return true;
        JOptionPane.showMessageDialog(null, "There's no valid path from the source to the destination!");
        return false;
    }     
      
    public void undoOrder(){
    	for (TechnologyLevel level:TechnologyLevel.values()){
    		int n = destination.getUsableTroopAmount(level, player);
    		for (int k = n; k < n + troopAmount.get(level); k++)
    			destination.getTroopList(level).get(k).setActioned(false);
    		for (int j = 0; j < troopAmount.get(level); j++){
    			Troop tr = destination.peekTroop(level, player);
     		   tr.setActioned(false);
     		   destination.removeTroop(level, player);
     		   source.addTroop(tr);
    		}
    	}
    }
    
    public  String printOrder(){
    	StringBuffer sentence = new StringBuffer();
    	sentence.append("Move");
    	for (TechnologyLevel level:TechnologyLevel.values())
    		if (troopAmount.get(level) > 0){
    		sentence.append(troopAmount.get(level));
    		sentence.append(" " + level + ", ");
    	}
    	sentence.append(" from " + source.getLocation() + " to " + destination.getLocation());
        return sentence.toString();
    }

	@Override
	public void executeOrder() {
		for (TechnologyLevel level:TechnologyLevel.values())
	     	   for (int j = 0; j < troopAmount.get(level); j++){
	    		   Troop tr = source.peekTroop(level, player);
	    		   tr.setActioned(true);
	    		   source.removeTroop(level, player);
	    		   destination.addTroop(tr);
	    	}
		
	}
    	
}
    
    

